package com.lin.handler;

import com.alibaba.fastjson2.JSONObject;
import com.lin.utils.LinResult;
import com.lin.utils.ResultCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * Copyright(C),2022年-12月-05,霖霖
 * FileNames:FileController
 * Author:霖霖
 * Date:2022/12/5 9:52
 * Description:
 * History:
 * <author>       <time>      <version>
 * 霖霖            2022/12/5      版本号
 */
@RestControllerAdvice
@Slf4j
public class HandlerArgsValidException {
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public LinResult handlerMethodArgumentNotValidException(MethodArgumentNotValidException e) {
        JSONObject errorMessage = new JSONObject();
        for (FieldError error : e.getBindingResult().getFieldErrors()) {
            errorMessage.put(error.getField(), error.getDefaultMessage());
        }
        log.info(errorMessage.toJSONString());
        return LinResult.error().code(ResultCode.VALID_FAIL).message("参数校验失败").data("errorInfo",errorMessage);
    }
}
